from abc import ABC, abstractmethod
from typing import Dict, Any, List

class BaseServiceHandler(ABC):
    """服务信息处理器基类"""
    
    @abstractmethod
    def get_service_details(self, service_info: Dict[str, Any]) -> List[str]:
        """获取服务详细信息的抽象方法"""
        pass
    
    def _safe_str(self, value: Any) -> str:
        """安全地将值转换为字符串"""
        if value is None:
            return ''
        return str(value).replace('<', '&lt;').replace('>', '&gt;')
    
    def _format_dict_items(self, items: Dict[str, Any], prefix: str = '') -> List[str]:
        """格式化字典项为字符串列表"""
        result = []
        for key, value in items.items():
            if isinstance(value, dict):
                result.extend(self._format_dict_items(value, f"{prefix}{key}: "))
            elif isinstance(value, list):
                result.append(f"{prefix}{key}: {', '.join(map(self._safe_str, value))}")
            else:
                result.append(f"{prefix}{key}: {self._safe_str(value)}")
        return result

class ServiceHandlerFactory:
    """服务处理器工厂类"""
    
    _handlers: Dict[str, BaseServiceHandler] = {}
    
    @classmethod
    def register_handler(cls, service_type: str, handler_class: type) -> None:
        """注册服务处理器"""
        if not issubclass(handler_class, BaseServiceHandler):
            raise ValueError(f"处理器类 {handler_class.__name__} 必须继承 BaseServiceHandler")
        cls._handlers[service_type] = handler_class()
    
    @classmethod
    def get_handler(cls, service_type: str) -> BaseServiceHandler:
        """获取服务处理器实例"""
        handler = cls._handlers.get(service_type)
        if not handler:
            from .default_handler import DefaultServiceHandler
            return DefaultServiceHandler()
        return handler 